﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Fluid;
using Fluid.Values;
using ZYing.LiquidThemeEngine.Config.Schemas;
using ZYing.LiquidThemeEngine.Config.Values;
using ZYing.LiquidThemeEngine.Objects;

namespace ZYing.LiquidThemeEngine
{
    public static class LiquidThemeViewRender
    {

        public static async ValueTask<string> RenderAsync(string theme, string view, LiquidThemeTemplateContext context)
        {
            if (string.IsNullOrWhiteSpace(theme)) throw new ArgumentNullException(nameof(theme));
            if (string.IsNullOrWhiteSpace(view)) throw new ArgumentNullException(nameof(view));
            if (context == null) throw new ArgumentNullException(nameof(context));
            var settings = await context.GetThemeSettingAsync();
            var options = context.LiquidThemeEngineOptions;
            context.SetTemplate(view);
            context.SetValue("settings", settings.Settings);
            context.Layout = Constants.DefaultLayout;
            var path = Helper.CombinePath(Constants.Directories.Templates, Helper.NormalTemplateFile(view));
            var template = await context.GetTemplateAsync(path);
            var body = await template.RenderAsync(context, options.TextEncoder);

            while (context.TryGetLayout(out var layout))
            {
                context.IncrementSteps();
                context.EnterChildScope();
                context.Layout = string.Empty;
                context.Body = body;
                var layoutPath = Helper.CombinePath(Constants.Directories.Layout, Helper.NormalTemplateFile(layout));
                var layoutTemplate = await context.GetTemplateAsync(layoutPath);
                body = await layoutTemplate.RenderAsync(context, options.TextEncoder);
                context.ReleaseScope();
            }
            return body;
        }
    }
}